package org.ioc.com.captchademo2.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.ioc.com.captchademo2.model.CaptchaPractices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    private final static long VAIRLD_SESSION_TIMEOUT=60*1000;
    @Autowired
    private CaptchaPractices captchaPractices;
    //生成一个验证码,并且返回给前端
    @RequestMapping("/get")
    public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        LineCaptcha lineCaptcha= CaptchaUtil.createLineCaptcha(captchaPractices.getWidth(),captchaPractices.getHeight());
        lineCaptcha.write(response.getOutputStream());
        String code = lineCaptcha.getCode();
        session.setAttribute(captchaPractices.getSession().getKey(),code);
        session.setAttribute(captchaPractices.getSession().getTime(),System.currentTimeMillis());
        response.getOutputStream().close();

    }

    //校验
    @RequestMapping("/check")
    public Boolean check(String inputcode,HttpSession session){
        /*
        基本校验我们已经实现
        但是还要考虑验证码过期
         */
        if (inputcode==null){
            return false;
        }
        String saveCode = (String) session.getAttribute(captchaPractices.getSession().getKey());
        long saveDate= (long) session.getAttribute(captchaPractices.getSession().getTime());
        if (System.currentTimeMillis()-saveDate<VAIRLD_SESSION_TIMEOUT){
            if (inputcode.equalsIgnoreCase(saveCode)){
                return true;
            }
        }
       return false;
    }
}
